package com.ego.auth.prop;

import com.ego.auth.utils.RsaUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@Data
@ConfigurationProperties(prefix = "ego.jwt")
public class JwtProperties {

    private String secret;// 登录校验的密钥
    private String pubKeyPath;
    private String priKeyPath;
    private Integer expire;
    private String cookieName;
    private Integer cookieMaxAge;

    private PrivateKey privateKey;
    private PublicKey publicKey;

    private static final Logger logger = LoggerFactory.getLogger(JwtProperties.class);


    @PostConstruct //构造函数执行之后执行下这个方法,有点类似于servlet的init方法
    public void init() {
        File priFile = new File(priKeyPath);
        File pubFile = new File(pubKeyPath);

        try {
            if (!priFile.exists() || !pubFile.exists()) {
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }
            //获取下私钥和公钥
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            logger.error("初始化公钥和私钥失败！", e);
            throw new RuntimeException();
        }
    }

}
